﻿#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "WebConfig.h"
#include "DataBaseConf.h"
#include <QDebug>
#include <QDir>
#include <QMessageBox>
#include <QProcess>
#include "Service.h"
#include "DataLoaderDialog.h"
#include "iostream"
#include <QDesktopServices>
#include "WebList.h"

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow), m_redis_process(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
#ifdef _DEBUG
    m_curDir = "D:/tools/dothing_server_manager";
#else
    m_curDir = QCoreApplication::applicationDirPath();
#endif

    ui->setupUi(this);
	connect(ui->buttonGotoWeb, SIGNAL(clicked()), this, SLOT(goIntoWebSysterm()));
	connect(ui->radioButtonStart_redis, SIGNAL(clicked()), this, SLOT(on_radioButtonStart_redis_clicked(bool)));
	connect(ui->radioButtonStop_redis, SIGNAL(clicked()), this, SLOT(on_radioButtonStop_redis_clicked(bool)));
	
    m_service.insert(ServiceType::APACHE,"DOTHING_WEB_SERVER");
    m_service.insert(ServiceType::MYSQL,"DOTHING_DATABASE_SERVER");
	m_service.insert(ServiceType::TASK, "DOTHING_TASK_SERVER");
	m_service.insert(ServiceType::MEMCACHE, "memcached Server");
	m_service.insert(ServiceType::WECHAT, "WechatServer");
	m_service.insert(ServiceType::NGINX, "nginx");
	//m_service.insert(ServiceType::REDIS, "Redis");

	flushUi();

	//创建托盘图标
	QIcon icon = QIcon(":/dothing/res/th_logo2.png");
	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setIcon(icon);
	trayIcon->setToolTip(tr("DOTHING服务管理器"));
	QString titlec = tr("DOTHING服务管理器");
	QString textc = tr("欢迎进入DOTHING服务管理器");
	trayIcon->show();

	//弹出气泡提示
	trayIcon->showMessage(titlec, textc, QSystemTrayIcon::Information, 5000);

	//添加单/双击鼠标相应
	connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
		this, SLOT(trayiconActivated(QSystemTrayIcon::ActivationReason)));

	//创建监听行为
	minimizeAction = new QAction(tr("最小化 (&I)"), this);
	connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
	restoreAction = new QAction(tr("还原 (&R)"), this);
	connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
	quitAction = new QAction(tr("退出 (&Q)"), this);
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

	//创建右键弹出菜单
	trayIconMenu = new QMenu(this);
	trayIconMenu->addAction(minimizeAction);
	trayIconMenu->addAction(restoreAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(quitAction);
	trayIcon->setContextMenu(trayIconMenu);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::flushUi()
{
    QDir apacheFile(m_curDir+"/server/apache/bin/httpd.exe");
    QDir mysqlFile(m_curDir+"/server/mysql/bin/mysqld.exe");
    QDir taskFile(m_curDir + "/server/task/DothingTask.exe");
	QDir memcacheFile(m_curDir + "/server/memcached.exe");
	QDir wechatFile(m_curDir + "/server/mywechat.exe");
	QDir nginxFile(m_curDir + "/server/nginx/nginx.exe");
	QDir redisFile(m_curDir + "/server/redis/redis-server.exe");
	QDir composerFile(m_curDir + "/server/redis/nginx.exe");

    ui->labelApache->setText(apacheFile.absolutePath());
	ui->labelMysql->setText(mysqlFile.absolutePath()); 
    ui->labelTask->setText(taskFile.absolutePath());
	ui->labelMemcache->setText(memcacheFile.absolutePath());
	ui->labelMemcache_3->setText(nginxFile.absolutePath());
	ui->labelMemcache_4->setText(wechatFile.absolutePath());
	/*ui->label_12->setText(composerFile.absolutePath());*/
	ui->label_17->setText(redisFile.absolutePath());

	if (Service::getStatus(m_service.value(ServiceType::APACHE).toStdWString())){
		ui->radioButtonApacheStart->setChecked(true);
	}
	else
	{
		ui->radioButtonApacheStop->setChecked(true);
	}

	if (Service::getStatus(m_service.value(ServiceType::MYSQL).toStdWString())){
		ui->radioButtonMysqlStart->setChecked(true);
	}
	else
	{
		ui->radioButtonMysqlStop->setChecked(true);
	}

	if (Service::getStatus(m_service.value(ServiceType::TASK).toStdWString())){
		ui->radioButtonTaskStart->setChecked(true);
	}
	else
	{
		ui->radioButtonTaskStop->setChecked(true);
	}

	if (Service::getStatus(m_service.value(ServiceType::MEMCACHE).toStdWString())){
		ui->radioButtonMemcacheStart->setChecked(true);
	}
	else
	{
		ui->radioButtonMemcacheStop->setChecked(true);
	}

	if (Service::getStatus(m_service.value(ServiceType::NGINX).toStdWString())){
		ui->radioButtonMemcacheStart_3->setChecked(true);
	}
	else
	{
		ui->radioButtonMemcacheStop_3->setChecked(true);
	}

	if (Service::getStatus(m_service.value(ServiceType::WECHAT).toStdWString())){
		ui->radioButtonMemcacheStart_4->setChecked(true);
	}
	else
	{
		ui->radioButtonMemcacheStop_4->setChecked(true);
	}
	
	//ui->radioButtonStop_redis->setChecked(true);

}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        mouse_press = true;
        move_point = event->pos();;
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    //若鼠标左键被按下
    if (mouse_press)
    {
        //鼠标相对于屏幕的位置
        QPoint move_pos = event->globalPos();
        //移动主窗体位置
        this->move(move_pos - move_point);
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    //设置鼠标为未被按下
    mouse_press = false;
}

void MainWindow::paintEvent(QPaintEvent *)
{
    QPainterPath path;
    path.setFillRule(Qt::WindingFill);
    path.addRect(10, 10, this->width() - 20, this->height() - 20);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.fillPath(path, QBrush(Qt::black));

    QColor color(210, 210, 210, 50);
    for (int i = 0; i < 10; i++)
    {
        QPainterPath path;
        path.setFillRule(Qt::WindingFill);
        path.addRect(10 - i, 10 - i, this->width() - (10 - i) * 2, this->height() - (10 - i) * 2);
        //color.setAlpha(150 - qSqrt(i) * 140);
        painter.setPen(color);
        painter.drawPath(path);
    }
    //QPainter painter(this);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);
}

void MainWindow::on_pushButtonWebSet_pressed()
{
	m_restartCmd = "net start DOTHING_WEB_SERVER";

	/*WebConfig *webConfig = new WebConfig();
	connect(webConfig, SIGNAL(webConfigSetOverSignal(QString)), this, SLOT(stopRe(QString)));
    webConfig->show();
	*/
	WebList *webList = new WebList();
	connect(webList, SIGNAL(webConfigSetOverSignal(QString)), this, SLOT(stopRe(QString)));
	webList->show();
}

void MainWindow::on_pushButtonWebSet_2_pressed()
{
	m_restartCmd = "net start DOTHING_WEB_SERVER";

	WebConfig *webConfig = new WebConfig();
	connect(webConfig, SIGNAL(webConfigSetOverSignal(QString)), this, SLOT(restartNginx(QString)));
	webConfig->show();
	
	/*WebList *webList = new WebList();
	connect(webList, SIGNAL(webConfigSetOverSignal(QString)), this, SLOT(stopRe(QString)));
	webList->show();*/
}
void MainWindow::on_pushButtonDatabaseSet_pressed()
{
    DataBaseConf *dataConfig = new DataBaseConf();
    dataConfig->show();
}

void MainWindow::startService(int serviceType)
{
	DataLoaderDialog::getInstance()->show();
    QString cmd = "net start \""+ m_service.value(serviceType)+"\"";

	serviceOperate(cmd, serviceType);
}

void MainWindow::stopService(int serviceType)
{
	DataLoaderDialog::getInstance()->show();
    QString cmd = "net stop \""+ m_service.value(serviceType)+"\"";

	serviceOperate(cmd, serviceType);
}



void MainWindow::on_radioButtonApacheStart_clicked(bool checked)
{
	if(checked){
        startService(ServiceType::APACHE);
    }
}

void MainWindow::on_radioButtonApacheStop_clicked(bool checked)
{
    if(checked){
        stopService(ServiceType::APACHE);
    }
}

void MainWindow::on_radioButtonMysqlStart_clicked(bool checked)
{
    if(checked){
        startService(ServiceType::MYSQL);
    }
}

void MainWindow::on_radioButtonMysqlStop_clicked(bool checked)
{
	//DataLoaderDialog::getInstance()->show();
    if(checked){
        stopService(ServiceType::MYSQL);
    }

}

void MainWindow::on_radioButtonTaskStart_clicked(bool checked)
{
	//DataLoaderDialog::getInstance()->show();
    if(checked){
        startService(ServiceType::TASK);
    }

}

void MainWindow::on_radioButtonTaskStop_clicked(bool checked)
{
	//DataLoaderDialog::getInstance()->show();
    if(checked){
        stopService(ServiceType::TASK);
    }

	if (Service::getStatus(m_service.value(ServiceType::TASK).toStdWString())){
		ui->radioButtonTaskStart->setChecked(true);
	}
	else
	{
		ui->radioButtonTaskStop->setChecked(true);
	}
}

void MainWindow::on_radioButtonMemcacheStart_clicked(bool checked)
{
	//DataLoaderDialog::getInstance()->show();
    if(checked){
		startService(ServiceType::MEMCACHE);
    }
    
}

void MainWindow::on_radioButtonMemcacheStart_3_clicked(bool checked)
{
	if (checked){
		QString cmd = m_curDir + "/server/php/php-cgi.exe -b 127.0.0.1:9000 -c " + m_curDir + "/server/php/php.ini";
		serviceOperate(cmd, ServiceType::NGINX);

		startService(ServiceType::NGINX);
	}

}

void MainWindow::on_radioButtonMemcacheStop_3_clicked(bool checked)
{
	if (checked){

		stopService(ServiceType::NGINX);

		QProcess taskkill;

		taskkill.execute("taskkill", QStringList() << "-im" << "nginx.exe" << "-f");

		QProcess phpTaskkill;

		phpTaskkill.execute("taskkill", QStringList() << "-im" << "php-cgi.exe" << "-f");
		
	}

}

void MainWindow::on_radioButtonMemcacheStop_clicked(bool checked)
{
	//DataLoaderDialog::getInstance()->show();
    if(checked){
		stopService(ServiceType::MEMCACHE);
    }

}

void MainWindow::on_radioButtonMemcacheStart_4_clicked(bool checked)
{
	if (checked){
		startService(ServiceType::WECHAT);
	}

}

void MainWindow::on_radioButtonMemcacheStop_4_clicked(bool checked)
{
	if (checked){
		stopService(ServiceType::WECHAT);
	}

}

void MainWindow::on_radioButtonStart_redis_clicked(bool checked)
{
	if (checked) {
		ui->radioButtonStop_redis->setChecked(false);
		ui->radioButtonStart_redis->setChecked(true);
		printf("here");
		startRedis();
	}

}

void MainWindow::on_radioButtonStop_redis_clicked(bool checked)
{
	if (checked) {
		ui->radioButtonStart_redis->setChecked(false);
		ui->radioButtonStop_redis->setChecked(true);
		stopRedis();
	}

}

void MainWindow::on_startALL_pressed()
{
    QMapIterator<int, QString> i(m_service);
    while (i.hasNext()) {
		DataLoaderDialog::getInstance()->show();
        i.next();
        startService(i.key());
    }
	//flushUi();
}

void MainWindow::on_stopALL_pressed()
{
    QMapIterator<int, QString> i(m_service);
    while (i.hasNext()) {
		//DataLoaderDialog::getInstance()->show();
        i.next();
        stopService(i.key());
    }
	//flushUi();
}

void MainWindow::trayiconActivated(QSystemTrayIcon::ActivationReason reason)
{
	switch (reason)
	{
	case QSystemTrayIcon::Trigger:
		//单击托盘图标
	case QSystemTrayIcon::DoubleClick:
		//双击托盘图标
		this->showNormal();
		this->raise();
		break;
	default:
		break;
	}
}

void MainWindow::endLoading()
{
	//DataLoaderDialog::getInstance()->show();
	flushUi();
	DataLoaderDialog::getInstance()->hide();
}

void MainWindow::serviceOperate(QString cmd ,int serviceType)
{
	QProcess *p = new QProcess();
	p->start(cmd);

	connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), p, SLOT(deleteLater()));
	connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(endLoading()));
}

/*进入系统*/
void MainWindow::goIntoWebSysterm()
{
	QSettings settings("web.ini", QSettings::IniFormat);
	QString port = settings.value("web/port").toString();

	QDesktopServices::openUrl(QUrl("http://localhost:" + port));
}

void MainWindow::stopRe(QString cmd)
{
	DataLoaderDialog::getInstance()->show();
	QProcess *p = new QProcess();
	p->start(cmd);

	connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), p, SLOT(deleteLater()));
	connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(startRe()));
}

void MainWindow::startRe()
{
	QProcess *p = new QProcess();
	p->start(m_restartCmd);

	connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), p, SLOT(deleteLater()));
	connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(endLoading()));
}

void MainWindow::restartNginx(QString cmd)
{
	DataLoaderDialog::getInstance()->show();
	on_radioButtonMemcacheStop_3_clicked(true);
	on_radioButtonMemcacheStart_3_clicked(true);

}
void MainWindow::startRedis() {
	DataLoaderDialog::getInstance()->show();
	QString redis = m_curDir+"/server/redis/redis-server.exe";
	m_redis_process = new QProcess();
	m_redis_process->start(redis);
	
	connect(m_redis_process, SIGNAL(finished(int, QProcess::ExitStatus)), m_redis_process, SLOT(deleteLater()));
	connect(m_redis_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(endLoading()));
	connect(m_redis_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(finishRedisSlot()));
	endLoading();

}

void MainWindow::stopRedis() {

	if (m_redis_process != NULL){
		m_redis_process->deleteLater();
	}
	
}
void MainWindow::finishRedisSlot() {
	m_redis_process = NULL;
}